import asyncio
import time
from time import sleep

# async def func():
#     print('你好阿，我叫陈一')
#
# if __name__ == '__main__':
#     g = func() # 此时的函数是异步协程函数，此时的函数执行得到的是一个协程对象
#     asyncio.run(g)  # 协程程序运行需要asyncio模块的支持


# async def func1():
#     print('你好阿，我叫小陈')
#     # sleep(3)   # 当程序出现了同步操作的时候（sleep为同步），异步就中断了
#     await asyncio.sleep(3) # 异步操作的代码 await 为挂起的意思
#     print('你好阿，我叫小小陈')
#
# async def func2():
#     print('你好阿，我叫小王')
#     # sleep(2)
#     await asyncio.sleep(2)
#     print('你好阿，我叫小王吧')
#
# async def func3():
#     print('你好阿，我叫小李')
#     # sleep(4)
#     await asyncio.sleep(4)
#     print('你好阿，我叫小小李')
#
#
# if __name__ == '__main__':
#     f1 = func1()
#     f2 = func2()
#     f3 = func3()
#
#     tasks = [f1,f2,f3]
#
#     # 开始时间
#     t1 = time.time()
#     # 一次性启动多个任务(协程)
#     asyncio.run(asyncio.wait(tasks))  # asyncio.wait 多个任务的固定搭配
#     # 结束时间
#     t2 = time.time()
#     print(f'耗时为：{t2-t1}')

'''
python官方希望你以下面这种方式写
'''

async def func1():
    print('你好阿，我叫小陈')
    await asyncio.sleep(3) # 异步操作的代码 await 为挂起的意思 一般await挂起操作放在协程对象前面
    print('你好阿，我叫小小陈')

async def func2():
    print('你好阿，我叫小王')
    await asyncio.sleep(2)
    print('你好阿，我叫小王吧')

async def func3():
    print('你好阿，我叫小李')
    await asyncio.sleep(4)
    print('你好阿，我叫小小李')

async def main():
    tasks = [asyncio.create_task(func1()),
             asyncio.create_task(func2()),
             asyncio.create_task(func3())
    ]
    await asyncio.wait(tasks)  # 前面需要加await才算异步

if __name__ == '__main__':
    t1 = time.time()
    asyncio.run(main())
    t2 = time.time()
    print(f'耗时为：{t2-t1}')


# 在爬虫领域的应用
async def download(url):
    print('准备开始下载!')
    await asyncio.sleep(3)  # 模拟网络请求 此处写的话不能为requests.get()
    print('下载完成!')

async def main():
    urls = [
        'http://www.baidu.com',
        'http://www.taobao.com',
        'http://www.12306.com'
    ]
    tasks = []
    for url in urls:
        d = asyncio.create_task(download(url))
        tasks.append(d)

    await asyncio.wait(tasks)

if __name__ == '__main__':
    asyncio.run(main())




